package com.tjf.lib_utils;

import android.content.Context;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Build;

import java.util.HashMap;
import java.util.Map;

/**
 * // 初始化 SoundPlayManager，最多同时播放 5 个音频
 * soundPlayManager = new SoundPlayManager(this, 5);
 * <p>
 * // 加载音频资源
 * int soundId = soundPlayManager.loadSound(R.raw.sample_sound);
 * <p>
 * // 播放音频，不循环，正常速率
 * soundPlayManager.playSound(soundId, 0, 1.0f);
 */
public class SoundPlayManager {
    private SoundPool soundPool;
    private Map<Integer, Integer> soundMap;
    private Context context;

    public SoundPlayManager(Context context, int maxStreams) {
        this.context = context;
        this.soundMap = new HashMap<>();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            AudioAttributes audioAttributes = new AudioAttributes.Builder()
                    .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                    .build();
            soundPool = new SoundPool.Builder()
                    .setAudioAttributes(audioAttributes)
                    .setMaxStreams(maxStreams)
                    .build();
        } else {
            // 兼容旧版本
            soundPool = new SoundPool(maxStreams, AudioManager.STREAM_MUSIC, 0);
        }
    }

    /**
     * 加载音频资源
     *
     * @param resId 资源 ID
     * @return 加载后的声音 ID
     */
    public int loadSound(int resId) {
        int soundId = soundPool.load(context, resId, 1);
        soundMap.put(resId, soundId);
        return soundId;
    }


    /**
     * 播放指定资源 ID 的音频
     *
     * @param resId 资源 ID
     * @param loop  是否循环播放，0 表示不循环，-1 表示无限循环
     * @param rate  播放速率，取值范围 0.5f - 2.0f
     */
    public void playSound(int resId, int loop, float rate) {
        Integer soundId = soundMap.get(resId);
        if (soundId != null) {
            soundPool.play(soundId, 1, 1, 1, loop, rate);
        }
    }

    /**
     * 播放音频
     */
    public void playSound(int resId) {
        //加载音频，获取音频load的ID
        loadSound(resId);
        // 异步需要等待加载完成，音频才能播放成功
        soundPool.setOnLoadCompleteListener((soundPool, sampleId, status) -> {
            if (status == 0) {
                playSound(resId, 0, 1);
            }
        });
    }

    /**
     * 停止指定资源 ID 的音频播放
     *
     * @param resId 资源 ID
     */
    public void stopSound(int resId) {
        Integer soundId = soundMap.get(resId);
        if (soundId != null) {
            soundPool.stop(soundId);
        }
    }

    /**
     * 释放 SoundPool 资源
     */
    public void release() {
        if (soundPool != null) {
            soundPool.release();
            soundPool = null;
            soundMap.clear();
        }
    }
}